﻿using Castle.Core.Logging;
using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WJP.DataPortal;
using WJP.Reflection;

namespace WJP.Environment
{
    /// <summary>
    /// 控制器拦截器
    /// </summary>
    public class ControllerInterceptor : IInterceptor
    {
        public ILogger Logger { get; set; }

        public ControllerInterceptor()
        {
            Logger = NullLogger.Instance;
        }

        public void Intercept(IInvocation invocation)
        {
            if (Attribute.IsDefined(invocation.TargetType, typeof(IgnoreProxyAttribute))
                || Attribute.IsDefined(invocation.Method, typeof(IgnoreProxyAttribute))
                || !PlatformEnvironment.NeetProxy())
            {
                invocation.Proceed();
            }
            else
            {
                try
                {
                    invocation.ReturnValue = PortalApi.Fetch(invocation.TargetType, new CallMethodInfo()
                    {
                        MethodName = invocation.Method.Name,
                        Parameters = invocation.Arguments,

                    });
                }
                catch (Exception ex)
                {
                    //Logger.ErrorFormat(ex, "控制器代理执行{0}方法{1}({2})失败".FormatArgs(invocation.TargetType, invocation.Method.Name, invocation.Arguments.Select(p => p.ToString()).JoinAsString(",")));

                    throw new ControllerProxyException("控制器代理执行{0}方法{1}({2})失败"
                        .FormatArgs(invocation.TargetType, invocation.Method.Name, invocation.Arguments.Select(p => p.ToString()).JoinAsString(",")) + ex);
                }
            }
        }
    }
}
